package com.abl.lib.common.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.util.ArrayList;

public class MathKit {

    /**
     * 两个整数之间的数(默认升序)
     *
     * @param o1   一个整数
     * @param o2   另一整数
     * @param sort 排序 "ASC"、"DESC"、NULL(就是升序)
     */
    public static ArrayList<Integer> numberBetweenTwoInt(Object o1, Object o2, String sort) {
        int int1 = Integer.parseInt(o1 + "");
        int int2 = Integer.parseInt(o2 + "");
        ArrayList<Integer> ints = new ArrayList<>();

        if (int1 == int2) {
            ints.add(int1);
            return ints;
        }

        if (int1 < int2) {
            for (int start = int1; start <= int2; start++) {
                ints.add(start);
            }
        }

        if (int1 > int2) {
            for (int start = int2; start <= int1; start++) {
                ints.add(start);
            }
        }

        if ("DESC".equals(sort)) {
            ints.sort((o11, o21) -> o21 - o11);
        }

        return ints;
    }

    /**
     * 加法
     */
    public static BigDecimal add(Object v1, Object v2, int scale) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        BigDecimal multiply = b1.add(b2);
        return multiply.setScale(scale, RoundingMode.DOWN);
    }

    /**
     * 减法
     */
    public static BigDecimal sub(Object v1, Object v2, int scale) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        BigDecimal multiply = b1.subtract(b2);
        return multiply.setScale(scale, RoundingMode.DOWN);
    }

    /**
     * 乘法
     */
    public static BigDecimal mul(Object v1, Object v2, int scale) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        BigDecimal multiply = b1.multiply(b2);
        return multiply.setScale(scale, RoundingMode.DOWN);
    }

    /**
     * 除法
     */
    public static BigDecimal div(Object v1, Object v2, int scale) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        return b1.divide(b2, scale, RoundingMode.DOWN);
    }

    /**
     * 计算MD5
     *
     * @param str 需要计算的字符串
     * @return 大写MD5值
     */
    public static String getMD5(String str) {
        String ret;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            ret = new BigInteger(1, md.digest()).toString(16);
            if (ret.length() == 31) {
                ret = "0" + ret;
            } else if (ret.length() == 30) {
                ret = "00" + ret;
            }
            return ret.toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
